package com.glela.controller;

import com.glela.common.constant.CommonConstants;
import com.glela.constant.BizConstant;
import com.glela.goods.model.vo.brand.BrandVo;
import com.glela.goods.service.BrandService;
import com.glela.platform.constant.ErrorEnum;
import com.glela.platform.model.User;
import com.glela.platform.model.response.ResponseBaseModel;
import com.glela.platform.model.response.ResponsePageModel;
import com.glela.platform.model.response.ResponseResultModel;
import com.glela.platform.service.UserService;
import com.glela.platform.util.ParameterUtils;
import com.glela.serial.model.request.RequestSerial;
import com.glela.serial.model.response.*;
import com.glela.serial.service.SerialService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 期资讯相关逻辑控制器
 * 
 * @author 卫耀华 2016-10-17
 * 
 */
@Controller
@RequestMapping(value = "/serial", produces = "application/json;charset=UTF-8")
public class SerialController extends BaseController {

	@Autowired
	private SerialService	serialService;
	@Autowired
	private BrandService	brandService;
	@Autowired
	private UserService		userService;

	/**
	 * 首页今日推荐
	 * 
	 * @author 卫耀华
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/todayRecommend", method = RequestMethod.POST, consumes = "application/json")
	public ResponseEntity<?> todayRecommend(@RequestBody RequestSerial request) {
		try {
			if (request.getUserId() == null) {
				request.setUserId(0L);
			}
			List<ResponseSerial> list = serialService.getSerialsToday(request.getUserId());
			return new ResponseEntity<>(new ResponseResultModel<>(list), HttpStatus.OK);
		} catch (Exception e) {
			getLOGGER().error("首页今日推荐异常", e);
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20000), HttpStatus.OK);
		}
	}

	/**
	 * 首页今日推荐旁边点更多
	 * 
	 * @author 卫耀华
	 * @date 2016-10-21
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/moreNomalSrials", method = RequestMethod.POST, consumes = "application/json")
	public ResponseEntity<?> moreNomalSrials(@RequestBody RequestSerial request) {
		try {
			// 验证分页参数 
			if (ParameterUtils.validParams(request.getPageNum(), request.getPageSize())) {
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20102), HttpStatus.OK);
			}
			if (request.getUserId() == null) {
				request.setUserId(0L);
			}
			List<ResponseSerial> list = serialService.getMoreNomalSerialList(request.getUserId(), request.getStartIndex(), request.getPageSize());
			int count = serialService.countMoreNomalSerialNum();
			return new ResponseEntity<>(new ResponseResultModel<>(new ResponsePageModel<ResponseSerial>(count, request.getPageSize(), request.getPageNum(), list)), HttpStatus.OK);
		} catch (Exception e) {
			getLOGGER().error("首页今日推荐旁边点更多异常", e);
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20000), HttpStatus.OK);
		}
	}

	/**
	 * 品牌下面的期(只显示商品个数不显示商品列表)
	 * 
	 * @author 卫耀华
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/serialsForBrand", method = RequestMethod.POST, consumes = "application/json")
	public ResponseEntity<?> serialsForBrand(@RequestBody RequestSerial request) {
		try {
			// 验证品牌id不为空
			if (ParameterUtils.validParams(request.getBrandId())) {
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20102), HttpStatus.OK);
			}
			// 查找一个status=1的品牌信息
			BrandVo vo = brandService.selectBrandById(request.getBrandId());
			if (vo == null) {
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20408), HttpStatus.OK);
			}
			List<SimpleSerialVo> list = serialService.selectSerialsByBrandId(request.getBrandId(), request.getStartIndex(), request.getPageSize());
			int count = serialService.countSerialsByBrandId(request.getBrandId());
			return new ResponseEntity<>(new ResponseResultModel<>(new ResponsePageModel<SimpleSerialVo>(count, request.getPageSize(), request.getPageNum(), list)), HttpStatus.OK);
		} catch (Exception e) {
			getLOGGER().error("品牌下面的期异常", e);
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20000), HttpStatus.OK);
		}
	}

	/**
	 * 福利社分页（福利社期下面只显示商品个数不显示商品列表）
	 * 
	 * @author 卫耀华
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/fulishe", method = RequestMethod.POST, consumes = "application/json")
	public ResponseEntity<?> fulishe(@RequestBody RequestSerial request) {
		try {
			if (ParameterUtils.validParams(request.getPageNum(), request.getPageSize())) {
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20102), HttpStatus.OK);
			}
			// 福利社期信息列表
			List<SimpleSerialVo> list = serialService.selectFulisheSerialList(request.getStartIndex(), request.getPageSize());
			int count = serialService.selectFulisheSerialNum();
			return new ResponseEntity<>(new ResponseResultModel<>(new ResponsePageModel<SimpleSerialVo>(count, request.getPageSize(), request.getPageNum(), list)), HttpStatus.OK);
		} catch (Exception e) {
			getLOGGER().error("福利社分页接口异常", e);
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20000), HttpStatus.OK);
		}
	}

	/**
	 * 达人社区
	 * 
	 * @author 卫耀华
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/masterCommunity", method = RequestMethod.POST, consumes = "application/json")
	public ResponseEntity<?> masterCommunity(@RequestBody RequestSerial request) {
		try {
			List<Integer> typeList = new ArrayList<Integer>();
			typeList.add(BizConstant.SHEQU_NEW);
			typeList.add(BizConstant.SHEQU_JIANGSHI);
			typeList.add(BizConstant.SHEQU_DAREN);
			typeList.add(BizConstant.SHEQU_GUANZHU);
			if (!typeList.contains(request.getTabIndex())) {
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20133), HttpStatus.OK);
			}
			if (BizConstant.SHEQU_GUANZHU == request.getTabIndex()) {// 关注页用户ID必须传
				if (request.getUserId() == null || request.getUserId() == 0L) {
					return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20102), HttpStatus.OK);
				}
			}
			if (request.getUserId() == null) {
				request.setUserId(0L);
			}
			List<ResponseTalentSerial> list = serialService.community(request.getTabIndex(), request.getUserId(), request.getStartIndex(), request.getPageSize());
			int count = serialService.countCommunity(request.getTabIndex(), request.getUserId());
			return new ResponseEntity<>(new ResponseResultModel<>(new ResponsePageModel<ResponseTalentSerial>(count, request.getPageSize(), request.getPageNum(), list)), HttpStatus.OK);
		} catch (Exception e) {
			getLOGGER().error("达人社区接口异常", e);
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20000), HttpStatus.OK);
		}
	}

	/**
	 * <dl>
	 * <dt>查询首页推荐标题列表</dt>
	 * </dl>
	 * @return ResponseEntity<?>
	 * @author zls
	 * @date 2017年7月7日 上午11:44:05
	 */
	@RequestMapping(value = "/getSerialsTitle", method = RequestMethod.POST)
	public ResponseEntity<?> getSerialsTitle() {
		String rslt = null;
		try {
			rslt = queryCacheResult();
			if (StringUtils.isEmpty(rslt)) {
				rslt = toResultModelJSON(this.serialService.findSerials());
			} else {
				return toRespEntity(rslt);
			}
		} catch (Exception e) {
			getLOGGER().error("查询期列表异常：{}", e.getMessage(), e);
			rslt = toErrorModelJSON(ErrorEnum.C20000);
		}
		return toRespEntity(toCacheResult(rslt));
	}

	/**
	 * <dl>
	 * <dt>查询首页推荐分类下详细信息</dt>
	 * </dl>
	 * @param requestSerial
	 * @return ResponseEntity<?>
	 * @author zls
	 * @date 2017年7月7日 下午4:20:18
	 */
	@RequestMapping(value = "/getSerialsTitleInfo", method = RequestMethod.POST)
	public ResponseEntity<?> getSerialsTitleInfo(@RequestBody RequestSerial requestSerial, HttpServletRequest request) {
		String rslt = null;
		try {
			if (ParameterUtils.validParams(requestSerial.getSerialId())) {
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20102), HttpStatus.OK);
			}
			rslt = queryCacheResult(requestSerial.getSerialId());
			if (StringUtils.isEmpty(rslt)) {
				rslt = toResultModelJSON(this.serialService.findSerialInfo(requestSerial));
			} else {
				return toRespEntity(rslt);
			}
		} catch (Exception e) {
			getLOGGER().error("查询期列表异常：{}", e.getMessage(), e);
			rslt = toErrorModelJSON(ErrorEnum.C20000);
		}
		return toRespEntity(toCacheResult(requestSerial.getSerialId(), rslt));
	}

	/**
	 * 普通期详情
	 * 
	 * @author 卫耀华
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/nomalSrialDetail", method = RequestMethod.POST, consumes = "application/json")
	public ResponseEntity<?> nomalSrialDetail(@RequestBody RequestSerial request) {
		try {
			if (ParameterUtils.validParams(request.getSerialId())) {
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20102), HttpStatus.OK);
			}
			if (request.getUserId() == null) {
				request.setUserId(0L);
			}
			if (request.getShareUserId() == null) {
				request.setShareUserId(0L);
			}
			ResponseSerialDetail rs = serialService.getNomalSerialDetailBySerialId(request.getUserId(), request.getShareUserId(), request.getSerialId());
			if (rs == null) {
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20137), HttpStatus.OK);
			}
			// 普通期浏览量+1
			serialService.updateNomalSerialSeeCount(request.getSerialId());
			return new ResponseEntity<>(new ResponseResultModel<ResponseSerialDetail>(rs), HttpStatus.OK);
		} catch (Exception e) {
			getLOGGER().info("普通期详情异常", e);
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20000), HttpStatus.OK);
		}
	}

	/**
	 * 达人期详情
	 * 
	 * @author 卫耀华
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/talentSrialDetail", method = RequestMethod.POST, consumes = "application/json")
	public ResponseEntity<?> talentSrialDetail(@RequestBody RequestSerial request) {
		try {
			if (ParameterUtils.validParams(request.getSerialId())) {
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20102), HttpStatus.OK);
			}
			if (request.getUserId() == null) {
				request.setUserId(0L);
			}
			if (request.getShareUserId() == null) {
				request.setShareUserId(0L);
			}
			// 获取达人期详情
			ResponseTalentSerialDetail detail = serialService.getTalentSerialDetailByTalentSerialId(request.getSerialId(), request.getUserId(), request.getShareUserId());
			if (detail == null) {
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20137), HttpStatus.OK);
			}
			// 顺便浏览量+1
			serialService.updateTalentSerialSeeCount(request.getSerialId());
			return new ResponseEntity<>(new ResponseResultModel<ResponseTalentSerialDetail>(detail), HttpStatus.OK);
		} catch (Exception e) {
			getLOGGER().info("达人期详情异常", e);
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20000), HttpStatus.OK);
		}
	}

	/**
	 * 浏览达人主页
	 * 
	 * @author 卫耀华
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/getTalentHomePage", method = RequestMethod.POST, consumes = "application/json")
	public ResponseEntity<?> getTalentHomePage(@RequestBody RequestSerial request) {
		try {
			if (ParameterUtils.validParams(request.getTalentId())) {
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20102), HttpStatus.OK);
			}
			if (request.getUserId() == null) {
				request.setUserId(0L);
			}
			User talentUser = userService.getUser(request.getTalentId());
			if (null == talentUser) {
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20113), HttpStatus.OK);
			}
			// 达人主页要展示的期
			List<SimpleSerialVo> list = serialService.selectTalentSerialByPagination(request.getTalentId(), request.getStartIndex(), request.getPageSize());
			int count = serialService.countTalentSerialNumByTalentId(request.getTalentId());
			//用户是否关注此达人
			int isEnjoy = userService.userIsEnjoyThisTalent(request.getTalentId(), request.getUserId());
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("talentId", talentUser.getId());// 达人ID、讲师ID
			map.put("personDescription", StringUtils.isEmpty(talentUser.getSynopsis()) ? "" : talentUser.getSynopsis());// 达人个人简介
			map.put("talentHeadPhoto", StringUtils.isEmpty(talentUser.getPicture()) ? "" : talentUser.getPicture());// 达人头像
			map.put("talentNickName", StringUtils.isEmpty(talentUser.getNickName()) ? "" : talentUser.getNickName());// 达人昵称
			map.put("isEnjoy", isEnjoy);// 是否关注了这个达人,Y或N回复
			map.put("backgroundImage", talentUser.getBackgroundImage());// 达人主页背景图
			map.put("fansCount", talentUser.getFansCount());// 粉丝数
			map.put("talentSerialList", new ResponsePageModel<SimpleSerialVo>(count, request.getPageSize(), request.getPageNum(), list));
			return new ResponseEntity<>(new ResponseResultModel<>(map), HttpStatus.OK);
		} catch (Exception e) {
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20000), HttpStatus.OK);
		}
	}

	/**
	 * 热门资讯
	 * 
	 * @author 卫耀华
	 * @date 2016-10-27
	 * @return
	 */
	@RequestMapping(value = "/hotSrials", method = RequestMethod.POST, consumes = "application/json")
	public ResponseEntity<?> hotSrials() {
		try {
			List<SimpleSerialVo> list = serialService.selectHotSerials();
			return new ResponseEntity<>(new ResponseResultModel<>(list), HttpStatus.OK);
		} catch (Exception e) {
			getLOGGER().error("热门资讯异常", e);
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20000), HttpStatus.OK);
		}
	}

	/**
	 * 达人进入个人的资讯
	 * 
	 * @author 卫耀华
	 * @date 2016-10-28
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/myTalentSerialList", method = RequestMethod.POST, consumes = "application/json")
	public ResponseEntity<?> myTalentSerialList(@RequestBody RequestSerial request) {
		try {
			if (request.getUserId() == null) {
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20102), HttpStatus.OK);
			}
			//达人进入我的资讯
			List<ResponseSerial> list = serialService.myTalentSerialList(request.getUserId(), request.getStartIndex(), request.getPageSize());
			int count = serialService.countMyTalentSerialList(request.getUserId());
			return new ResponseEntity<>(new ResponseResultModel<>(new ResponsePageModel<ResponseSerial>(count, request.getPageSize(), request.getPageNum(), list)), HttpStatus.OK);
		} catch (Exception e) {
			getLOGGER().error("达人进入我的资讯异常", e);
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20000), HttpStatus.OK);
		}
	}

	/**
	 * 查询达人期
	 * 
	 * @author chengzhequan
	 * @date 2016年10月31日19:44:38
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/selectTalentSerial", method = RequestMethod.POST, consumes = "application/json")
	public ResponseEntity<?> selectTalentSerial(@RequestBody RequestSerial request) {
		try {
			if (ParameterUtils.validParams(request.getSerialId())) {
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20102), HttpStatus.OK);
			}
			ResponseSerialVo responseSerialVo = serialService.selectTalentSerial(request.getSerialId(), request.getUserId());
			return new ResponseEntity<>(new ResponseResultModel<ResponseSerialVo>(responseSerialVo), HttpStatus.OK);
		} catch (Exception e) {
			getLOGGER().error("查询达人期异常", e);
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20000), HttpStatus.OK);
		}
	}
	/**
	 * @Description: 查询首页推荐分类下详细信息（新）
	 * @Author: zhangrenjie
	 * @Date: 2018/1/12 16:38
	 *
	 */
	@RequestMapping(value = "/getSerialsTitleInfoNew", method = RequestMethod.POST)
	public ResponseEntity<?> getSerialsTitleInfoNew(@RequestBody RequestSerial requestSerial, HttpServletRequest request) {
		String rslt = null;
		String key = null;
		try {
			/*if (ParameterUtils.validParams(requestSerial.getSerialId())) {
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20102), HttpStatus.OK);
			}*/
			String phoneType = CommonConstants.PHONE_CLIENT_ANDROID;//默认值
			if (!StringUtils.isBlank(request.getHeader("phoneType"))) {
				phoneType = request.getHeader("phoneType").toLowerCase();
			}
			if(requestSerial.getUserId() > 0) {
				phoneType = requestSerial.getUserId() + phoneType;
			}
			if(requestSerial.getSerialId() > 0) {
				phoneType = requestSerial.getSerialId() + phoneType;
			}
			key = getTempCacheKey(CommonConstants.SERIALS_TITLE_INFO_NEW,phoneType);
			rslt = queryCacheResult(key);
//			rslt = queryCacheResult(requestSerial.getSerialId());
			if (StringUtils.isEmpty(rslt)) {
				rslt = toResultModelJSON(this.serialService.findSerialInfoNew(requestSerial,request));
			} else {
				return toRespEntity(rslt);
			}
		} catch (Exception e) {
			getLOGGER().error("查询期轮播图列表接口异常：{}", e.getMessage(), e);
//			rslt = toErrorModelJSON(ErrorEnum.C20000);
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20000), HttpStatus.OK);
		}
		return toRespEntity(toCacheResult(key, rslt));
//		return toRespEntity(toCacheResult(requestSerial.getSerialId(), rslt));
	}
}
